# encoding: utf-8
"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '17/10/2024'
    comment: 流程角色
"""
from fastapi import APIRouter, Request, Body, Query

from config import Config
from project.core.exception import BizError
from project.core.function import json_response
from project.lib.decorator import api_common, exec_duration
from project.lib.constant import DEFAULT_VALUE
from project.model.database.flow import FlowRole
from project.service.flow import FlowService


role_router = APIRouter(prefix='/m', tags=['manager.role'])


@role_router.post('/flow/role/add', summary='新增角色')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), verify_login=True)
@exec_duration(add_return=True)
async def do_node_role_add(request: Request,
                           name: str = Body(..., max_length=50, title='角色名称'),
                           phone: str = Body(..., max_length=20, title='手机号'),
                           flow_id: int = Body(..., title='服务流程id'),
                           remark: str = Body('', max_length=200, title='角色备注'),
                           session=None,
                           body_params=None):
    """
    **desc**: 新增流程角色

    **url**: http(s)://{0}.udicaria.com/m/flow/role/add

    **method**: POST

    **params**:

        <body>:
            name: 角色名称
            phone: 手机号
            flow_id: 服务流程id
            remark: 角色备注

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    role = await FlowService.do_role_add(session, body_params)

    return json_response(data=role.dict('id'))


@role_router.post('/flow/role/update', summary='修改角色')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), verify_login=True)
@exec_duration(add_return=True)
async def do_node_role_update(request: Request,
                              id: int = Body(..., title='角色id'),
                              name: str = Body(DEFAULT_VALUE, max_length=50, title='角色名称'),
                              phone: str = Body(DEFAULT_VALUE, max_length=20, title='手机号'),
                              remark: str = Body(DEFAULT_VALUE, max_length=200, title='角色备注'),
                              session=None,
                              body_params=None):
    """
    **desc**: 修改流程角色

    **url**: http(s)://{0}.udicaria.com/m/flow/role/update

    **method**: POST

    **params**:

        <body>:
            id: 角色id
            name: 角色名称
            phone: 手机号
            flow_id: 服务流程id
            remark: 角色备注

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    role = await FlowRole.fetch_one(session, wheres=(FlowRole.id == id))
    if not role:
        raise BizError('角色不存在')
    if not phone:
        raise BizError('手机号不能为空')
    # 判断角色名称是否已存在
    _role = await FlowRole.fetch_one(session, wheres=(FlowRole.id != id, FlowRole.flow_id == role.flow_id, FlowRole.name == name, ~FlowRole.is_deleted))
    if _role:
        raise BizError('该角色名称已存在')
    # 判断手机号是否已被绑定
    role = await FlowRole.fetch_one(session, wheres=(FlowRole.id != id, FlowRole.flow_id == role.flow_id, FlowRole.phone == phone, ~FlowRole.is_deleted))
    if role:
        raise BizError('该手机号已绑定角色')
    await FlowRole.create_modify(session,
                                 wheres=(FlowRole.id == id),
                                 **body_params.dict(),
                                 no_record_error=True)

    return json_response()


@role_router.get('/flow/role/list', summary='角色列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), verify_login=True)
@exec_duration(add_return=True)
async def do_flow_role_list(request: Request,
                            flow_id: int = Query(..., title='服务流程id'),
                            session=None):
    """
    **desc**: 流程角色列表

    **url**: http(s)://{0}.udicaria.com/m/node/role/list

    **method**: GET

    **params**:

        <body>:
            flow_id: 服务流程id

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: [
                {
                    name: 角色名称
                    flow_id: 服务流程id
                    flow_code: 服务流程编号
                    remark: 备注
                }
            ]
            exec_time: 接口后端处理时长
        }
    """
    data = await FlowRole.fetch_all(session, wheres=(FlowRole.flow_id == flow_id, ~FlowRole.is_deleted), orders=(FlowRole.id,))

    return json_response(data=[v.dict() for v in data])


@role_router.get('/flow/role/detail', summary='角色详情')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), verify_login=True)
@exec_duration(add_return=True)
async def do_flow_role_detail(request: Request,
                              id: int = Query(..., title='角色id'),
                              session=None):
    """
    **desc**: 流程角色详情

    **url**: http(s)://{0}.udicaria.com/m/node/role/detail

    **method**: GET

    **params**:

        <body>:
            id: 角色id

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: {
                name: 角色名称
                flow_id: 服务流程id
                flow_code: 服务流程编号
                remark: 备注

            }
            exec_time: 接口后端处理时长
        }
    """
    flow_role = await FlowRole.fetch_one(session, wheres=(FlowRole.id == id))
    if not flow_role:
        return json_response()

    return json_response()


@role_router.post('/flow/role/delete', summary='删除角色')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def do_flow_role_delete(request: Request, id: int = Body(..., title='角色id', embed=True), session=None):
    """
    **desc**: 删除角色

    **url**: http(s)://{0}.udicaria.com/m/flow/role/delete

    **method**: POST

    **params**:

        <body>:
            id: 角色id

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    await FlowService.do_delete_role(session, flow_role_id=id)

    return json_response()
